package com.example.webserviceclient;

import com.example.webserviceclient.pojo.CxfFileWrapper;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.xml.namespace.QName;
import java.io.File;
import java.net.URL;

/**
 * @author 陈乐
 * @version 1.0.0
 * @ClassName Main.java
 * @Description TODO
 * @createTime 2022年01月05日 15:52:00
 */
public class Main {

    public static void main(String[] args) {
        upload();
    }

    /**
     * 1.代理类工厂的方式,需要拿到对方的接口地址, 同时需要引入接口
     */
//    public static void invokeService_1() {
//        // 接口地址
//        String address = "http://localhost:8080/services/ws/api?wsdl";
//        // 代理工厂
//        JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
//        // 设置代理地址
//        jaxWsProxyFactoryBean.setAddress(address);
//        // 设置接口类型
//        jaxWsProxyFactoryBean.setServiceClass(ServerServiceDemo.class);
//        // 创建一个代理接口实现
//        ServerServiceDemo us = (ServerServiceDemo) jaxWsProxyFactoryBean.create();
//        // 数据准备
//        String data = "hello world";
//        // 调用代理接口的方法调用并返回结果
//        String result = us.emrService(data);
//        System.out.println("返回结果:" + result);
//    }

    /**
     * 2. 动态调用
     */
    public static void invokeService_2() {
        // 创建动态客户端
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient("http://localhost:8080/services/ws/api?wsdl");
        // 需要密码的情况需要加上用户名和密码
        // client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME, PASS_WORD));
        Object[] objects = new Object[0];
        try {
            // invoke("方法名",参数1,参数2,参数3....);
            //这里注意如果是复杂参数的话，要保证复杂参数可以序列化
            objects = client.invoke("emrService", "hello world");
            System.out.println("返回数据:" + objects[0]);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //上床文件
    private static final QName SERVICE_NAME = new QName("http://service.webserviceserver.example.com/", "WebServices");

    public static void upload() {
        URL wsdlURL = FileWSImplService.WSDL_LOCATION;
        FileWSImplService ss = new FileWSImplService(wsdlURL);
        FileWS port = ss.getFileWSImplPort();

//        文件上传
        {
            System.out.println("Invoking upload...");
            CxfFileWrapper _upload_file = new CxfFileWrapper();
            _upload_file.setFileName("test.csv");
            _upload_file.setFileExtension("csv");
            DataSource source = new FileDataSource(new File("d:\\test.csv"));
            _upload_file.setFile(new DataHandler(source));
            boolean _upload__return = port.upload(_upload_file);
            System.out.println("upload.result=" + _upload__return);
        }

        System.exit(0);
    }
}
